<template>
  <el-table
    :data="content"
    height="calc(100vh - 200px)"
    style="width: 100%"
    :cell-style="{
      padding: '6px 0',
      margin: '0',
      cursor: 'pointer',
      backgroundColor: 'transparent',
    }"
    :header-cell-style="{
      padding: '8px 0',
      margin: '0',
      background: 'none',
      backgroundColor: 'transparent',
    }"
    :row-style="{ backgroundColor: 'transparent' }"
    :header-row-style="{ backgroundColor: 'transparent' }"
    @row-click="showResponse"
  >
    <el-table-column label="编号 / 机场" width="120px">
      <template #default="scope">
        <div class="notam-element">{{ scope.row.number }}</div>
        <div class="notam-element">{{ scope.row.type }}</div>
        <span
          class="notam-element airport-tag"
          :style="{
            backgroundColor: airportColors[scope.row.airport]
              ? airportColors[scope.row.airport]
              : '#909399',
          }"
        >
          {{ scope.row.airport }}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="有效期 / 状态" width="180px">
      <template #default="scope">
        <div class="notam-element">{{ scope.row.effectiveTime }}</div>
        <div
          class="notam-element"
          v-if="scope.row.expirationTime == '2099-12-31 23:59:59'"
        >
          PERM
        </div>
        <div class="notam-element" v-else>{{ scope.row.expirationTime }}</div>
        <div
          class="notam-element"
          :style="{
            fontWeight: 'bold',
            color:
              validEffectiveStatus(scope.row) == '已失效'
                ? '#909399'
                : validEffectiveStatus(scope.row) == '未生效'
                ? '#409EFF'
                : '#67C23A',
          }"
        >
          {{ validEffectiveStatus(scope.row) }}
        </div>
      </template>
    </el-table-column>
    <el-table-column label="通告正文" prop="text">
      <template #default="scope">
        <div class="notam-element">
          <div v-if="lineBreaks">
            <div v-for="line in scope.row.text.split('\n')">
              {{ line.replace(/＂/g, "'") }}
            </div>
          </div>
          <div v-else>
            {{ scope.row.text.replace(/\n/g, "  ").replace(/＂/g, "'") }}
          </div>
        </div>
      </template>
      <template #header>
        <div class="header-element">
          <div style="width: 120px">通告正文</div>
          <div class="header-element-content">
            <el-tooltip effect="dark" placement="top-start">
              <template #content>
                <b>关键字检索说明：</b><br />
                如需多个关键字使用空格分开；<br />
                关键字前输入减号可排除关键字。<br />
                *例如<b>RWY 关闭 -滑行道</b><br />
                *单击可填入该示例
              </template>
              <el-button
                type="info"
                link
                icon="QuestionFilled"
                size="large"
                @click="keyword = 'RWY 关闭 -滑行道'"
              ></el-button>
            </el-tooltip>
            <div style="width: 200px">
              <el-input
                v-model="keyword"
                clearable
                placeholder="关键字检索"
                size="small"
              ></el-input>
            </div>
            <el-tooltip effect="dark" placement="top-start">
              <template #content>
                选中此项将不显示<br />
                <b>未生效</b>以及<b>48H内已失效</b><br />
                的NOTAM
              </template>
              <el-checkbox
                v-model="effectiveOnly"
                size="small"
                style="margin-left: 12px"
                >仅生效</el-checkbox
              >
            </el-tooltip>
            <!-- <el-checkbox v-model="sizeLarge" size="small">更大</el-checkbox> -->
            <el-checkbox v-model="lineBreaks" size="small">换行</el-checkbox>
          </div>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { h, ref, computed, onMounted, onUnmounted } from "vue";
import useNotamStore from "@/store/notam.js";
import useSeatStore from "@/store/seat.js";
import dayjs from "dayjs";
import { ElMessage, ElMessageBox } from "element-plus";
const notamStore = useNotamStore();
const seatStore = useSeatStore();

const airportColors = computed(() => {
  let atisColors = {};
  if (seatStore.atis) {
    for (let i = 0; i < seatStore.atis.length; i++) {
      atisColors[seatStore.atis[i].airportCode] = seatStore.atis[i].color;
    }
  }

  let colors = {
    ZUUU: atisColors["ZUUU"] ?? "#46B",
    ZUTF: atisColors["ZUTF"] ?? "#585",
    ZUMY: atisColors["ZUMY"] ?? "#859",
    ZULZ: atisColors["ZULZ"] ?? "#789",
    ZUYB: atisColors["ZUYB"] ?? "#789",
  };
  return colors;
});
const keyword = ref("");
const effectiveOnly = ref(false);
const sizeLarge = ref(false);
const tableSize = computed(() => (sizeLarge.value ? "large" : "small"));
const lineBreaks = ref(true);
const content = computed(() =>
  notamStore.content.filter((cell) => {
    if (effectiveOnly.value == true && validEffectiveStatus(cell) != "生效中") {
      return false;
    }
    if (keyword.value === "") {
      return true;
    }
    let keywordArray = keyword.value.split(" ");
    for (let i = 0; i < keywordArray.length; i++) {
      let kwd = keywordArray[i];
      let not = false;
      if (keywordArray[i].substr(0, 1) == "-") {
        kwd = keywordArray[i].substr(1, keywordArray[i].length - 1);
        not = true;
      }
      if (
        (not && !cell.text.includes(kwd)) ||
        (!not && cell.text.includes(kwd))
      ) {
        //
      } else {
        return false;
      }
    }
    return true;
  })
);

const validEffectiveStatus = (cell) => {
  let day = dayjs();
  return day.isAfter(cell.expirationTime)
    ? "已失效"
    : day.isBefore(cell.effectiveTime)
    ? "未生效"
    : "生效中";
};

const refresh = () => {
  ElMessage("正在刷新NOTAM(预计需要30秒)……");
  notamStore
    .refresh(1)
    .then((refreshResponse) => {
      console.log(refreshResponse);
      if (refreshResponse.count == 0) {
        ElMessage.danger("NOTAM刷新失败出错了(从SIPDS中检索到0条数据)");
      } else {
        notamStore
          .load()
          .then((loadResponse) => {
            ElMessage.success(`NOTAM刷新成功(共${notamStore.count}条)`);
            console.log(loadResponse);
          })
          .catch((error) => {
            ElMessage.danger(JSON.stringify(error, null, 2));
          });
      }
    })
    .catch((error) => {
      ElMessage.danger(JSON.stringify(error, null, 2));
    });
};

const counting = () => {
  return content.value.length;
};

defineExpose({ refresh, counting });

const showResponse = (item) => {
  console.log(item);
  ElMessageBox({
    title: "SIPDS原始数据",
    message: h(
      "textarea",
      {
        readonly: "readonly",
        style: {
          width: "calc(100vw - 120px)",
          maxWidth: "480px",
          height: "360px",
          resize: "none",
          backgroundColor: "rgba(128,128,128,0.1)",
          fontFamily: "Consolas,monospace",
        },
      },
      JSON.stringify(item.origion, null, 2)
        .replace(/＂/g, "'")
        .replace(/\\n/g, "\n")
    ),
  });
};
</script>

<style scoped>
.header-element {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 12px;
}
.header-element-content {
  min-width: 300px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.header-element-content > * {
  margin: 0;
  padding: 0;
  margin-right: 12px;
}

.header-element-content > last-child {
  margin: 0;
}

.airport-tag {
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  border-radius: 6px;
  font-size: 12px;
  color: #fff;
  width: 60px;
  height: 20px;
  /* padding: 0px 4px; */
  text-shadow: -1px -1px 8px #000a, 1px 1px 8px #000a;
}
</style>
